package cn.appkf.flappybird.net;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import cn.appkf.flappybird.actor.MyActor;
import cn.appkf.flappybird.stage.TestStage;

/**
 * Created by Administrator on 2016/8/3.
 */
public class NetWorker implements Runnable {



    private int port;
    private TestStage stage;

    private Socket socket;
    private PrintWriter os;
    private String ip;

    public NetWorker(String ip,int port, TestStage stage) {
        this.port = port;
        this.ip = ip;
        this.stage = stage;
    }

    @Override
    public void run() {

        try {
            socket=new Socket(ip,port);

            os=new PrintWriter(socket.getOutputStream());

            BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
            String line;


            MyActor actor=stage.getActor();
            JSONObject jo=new JSONObject();
            jo.put("id",actor.getID());
            jo.put("type","push");

            JSONObject act=new JSONObject();
            act.put("MapX",actor.getMapX());
            act.put("MapY",actor.getMapY());
            jo.put("actor",act);

            this.send(jo.toString());

            line=is.readLine();
            while(!line.equals("bye")){
                if(stage!=null){
                    stage.getMsg(line);
                }
                line=is.readLine();
            }

            os.close(); //关闭Socket输出流
            is.close(); //关闭Socket输入流
            socket.close(); //关闭Socket

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void send(String msg){
        os.println(msg);
        os.flush();
    }
}
